'use client';

import * as React from 'react';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import Menu from '@mui/material/Menu';
import MenuIcon from '@mui/icons-material/Menu';
import Container from '@mui/material/Container';
import Button from '@mui/material/Button';
import MenuItem from '@mui/material/MenuItem';
import SchoolIcon from '@mui/icons-material/School';
import SmartToyIcon from '@mui/icons-material/SmartToy';
import PeopleIcon from '@mui/icons-material/People';
import WorkIcon from '@mui/icons-material/Work';
import WorkHistoryIcon from '@mui/icons-material/WorkHistory';  // 添加新的图标导入
import Link from 'next/link';
import Avatar from '@mui/material/Avatar';
import Tooltip from '@mui/material/Tooltip';
import PersonIcon from '@mui/icons-material/Person';
import LogoutIcon from '@mui/icons-material/Logout';
import Badge from '@mui/material/Badge';
import { useRouter } from 'next/navigation';
import { alpha, useTheme } from '@mui/material/styles';
import EmailIcon from '@mui/icons-material/Email';

const pages = [
  { title: '首页', href: '/' },
  { title: '企业服务', href: '/enterprise' },
  { title: '校友圈', href: '/alumni-network', icon: 'people' },
  { title: '企业招聘直通车', href: '/recruitment', icon: 'work' },
  { title: 'AI 面试', href: '/job-assistant', icon: 'workHistory' },  // 修改导航项名称为"AI 面试"
  { title: '企业大模型', href: '/enterprise-ai', icon: 'smartToy' },
];

// 用户菜单项
const userMenuItems = [
  { title: '个人主页', href: '/profile', icon: <PersonIcon fontSize="small" /> },
];

function Navbar() {
  const router = useRouter();
  const theme = useTheme();
  const [anchorElNav, setAnchorElNav] = React.useState<null | HTMLElement>(null);
  const [anchorElUser, setAnchorElUser] = React.useState<null | HTMLElement>(null);
  const [user, setUser] = React.useState<any>(null);

  React.useEffect(() => {
    // 检查用户登录状态
    const checkLoginStatus = () => {
      // 从localStorage获取用户信息和token
      const userData = localStorage.getItem('user');
      const token = localStorage.getItem('token');

      console.log('导航栏检查登录状态:', {
        hasUserData: !!userData,
        hasToken: !!token,
        userDataLength: userData?.length || 0,
        tokenLength: token?.length || 0
      });

      // 添加调试信息
      if (process.env.NODE_ENV !== 'production') {
        try {
          if (userData) {
            console.log('用户数据前50个字符:', userData.substring(0, 50) + '...');
          }
          if (token) {
            console.log('Token前20个字符:', token.substring(0, 20) + '...');
          }
        } catch (debugError) {
          console.error('调试信息错误:', debugError);
        }
      }

      if (userData && token) {
        try {
          const parsedUser = JSON.parse(userData);

          // 验证用户数据是否有效
          if (!parsedUser || !parsedUser.id || !parsedUser.username) {
            console.error('用户数据无效:', parsedUser);
            throw new Error('用户数据缺少必要字段');
          }

          setUser(parsedUser);
          console.log('用户已登录:', parsedUser.username, '用户ID:', parsedUser.id);
        } catch (err) {
          console.error('解析用户数据失败:', err);
          // 清除无效的用户数据
          localStorage.removeItem('user');
          localStorage.removeItem('token');
          setUser(null);
        }
      } else {
        // 确保用户状态为未登录
        setUser(null);
      }
    };

    // 初始检查
    checkLoginStatus();

    // 添加存储事件监听器，当localStorage变化时更新状态
    const handleStorageChange = () => {
      checkLoginStatus();
    };

    window.addEventListener('storage', handleStorageChange);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);

  const handleOpenNavMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorElNav(event.currentTarget);
  };

  const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorElUser(event.currentTarget);
  };

  const handleCloseNavMenu = () => {
    setAnchorElNav(null);
  };

  const handleCloseUserMenu = () => {
    setAnchorElUser(null);
  };

  const handleLogout = () => {
    // 清除本地存储的token和用户信息
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    localStorage.removeItem('userData');

    // 触发存储事件，确保其他组件能感知到变化
    window.dispatchEvent(new Event('storage'));

    // 更新组件状态
    setUser(null);
    handleCloseUserMenu();

    // 显示成功消息
    alert('您已成功退出登录');

    // 跳转到登录页面
    router.push('/login');
  };

  const getInitials = () => {
    return user?.username
      ? user.username.charAt(0).toUpperCase()
      : 'U';
  };

  return (
    <AppBar
      position="static"
      color="default"
      elevation={1}
      sx={{
        backdropFilter: 'blur(20px)',
        backgroundColor: alpha('#fff', 0.9),
      }}
    >
      <Container maxWidth="xl">
        <Toolbar disableGutters>
          <SchoolIcon sx={{ display: { xs: 'none', md: 'flex' }, mr: 1 }} />
          <Typography
            variant="h6"
            noWrap
            component={Link}
            href="/"
            sx={{
              mr: 2,
              display: { xs: 'none', md: 'flex' },
              fontWeight: 700,
              color: 'inherit',
              textDecoration: 'none',
            }}
          >
            校友宝
          </Typography>

          <Box sx={{ flexGrow: 1, display: { xs: 'flex', md: 'none' } }}>
            <IconButton
              size="large"
              aria-label="navigation menu"
              aria-controls="menu-appbar"
              aria-haspopup="true"
              onClick={handleOpenNavMenu}
              color="inherit"
            >
              <MenuIcon />
            </IconButton>
            <Menu
              id="menu-appbar"
              anchorEl={anchorElNav}
              anchorOrigin={{
                vertical: 'bottom',
                horizontal: 'left',
              }}
              keepMounted
              transformOrigin={{
                vertical: 'top',
                horizontal: 'left',
              }}
              open={Boolean(anchorElNav)}
              onClose={handleCloseNavMenu}
              sx={{
                display: { xs: 'block', md: 'none' },
              }}
            >
              {pages.map((page) => (
                <MenuItem
                  key={page.title}
                  onClick={handleCloseNavMenu}
                  component={Link}
                  href={page.href}
                >
                  <Typography textAlign="center" sx={{ display: 'flex', alignItems: 'center' }}>
                    {page.icon === 'smartToy' && (
                      <SmartToyIcon fontSize="small" sx={{ mr: 0.5, verticalAlign: 'middle' }} />
                    )}
                    {page.icon === 'people' && (
                      <PeopleIcon fontSize="small" sx={{ mr: 0.5, verticalAlign: 'middle' }} />
                    )}
                    {page.icon === 'work' && (
                      <WorkIcon fontSize="small" sx={{ mr: 0.5, verticalAlign: 'middle' }} />
                    )}
                    {page.icon === 'workHistory' && (
                      <WorkHistoryIcon fontSize="small" sx={{ mr: 0.5, verticalAlign: 'middle' }} />
                    )}
                    {page.title}
                  </Typography>
                </MenuItem>
              ))}
              {user && (
                <MenuItem
                  onClick={handleCloseNavMenu}
                  component={Link}
                  href="/profile"
                >
                  <Typography textAlign="center" sx={{ display: 'flex', alignItems: 'center' }}>
                    <PersonIcon fontSize="small" sx={{ mr: 0.5, verticalAlign: 'middle' }} />
                    个人中心
                  </Typography>
                </MenuItem>
              )}
            </Menu>
          </Box>

          <SchoolIcon sx={{ display: { xs: 'flex', md: 'none' }, mr: 1 }} />
          <Typography
            variant="h5"
            noWrap
            component={Link}
            href="/"
            sx={{
              mr: 2,
              display: { xs: 'flex', md: 'none' },
              flexGrow: 1,
              fontWeight: 700,
              color: 'inherit',
              textDecoration: 'none',
            }}
          >
            校友宝
          </Typography>

          <Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}>
            {pages.map((page) => (
              <Button
                key={page.title}
                component={Link}
                href={page.href}
                onClick={handleCloseNavMenu}
                sx={{
                  my: 2,
                  color: (page.title === '企业大模型' || page.title === '校友圈') ? 'primary.main' : 'inherit',
                  display: 'flex',
                  alignItems: 'center',
                  fontWeight: (page.title === '企业大模型' || page.title === '校友圈') ? 'bold' : 'normal',
                }}
              >
                {page.icon === 'smartToy' && (
                  <SmartToyIcon fontSize="small" sx={{ mr: 0.5 }} />
                )}
                {page.icon === 'people' && (
                  <PeopleIcon fontSize="small" sx={{ mr: 0.5 }} />
                )}
                {page.icon === 'work' && (
                  <WorkIcon fontSize="small" sx={{ mr: 0.5 }} />
                )}
                {page.icon === 'workHistory' && (
                  <WorkHistoryIcon fontSize="small" sx={{ mr: 0.5 }} />
                )}
                {page.title}
              </Button>
            ))}
          </Box>

          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            {user ? (
              <>
                <Button
                  component={Link}
                  href="/profile"
                  sx={{
                    display: { xs: 'none', md: 'flex' },
                    alignItems: 'center',
                    mr: 2,
                    color: 'primary.main',
                    fontWeight: 500,
                    '&:hover': {
                      backgroundColor: alpha(theme.palette.primary.main, 0.08),
                    },
                  }}
                  startIcon={<PersonIcon />}
                >
                  个人中心
                </Button>
                <Box
                  sx={{
                    display: 'flex',
                    alignItems: 'center',
                    border: `1px solid ${alpha(theme.palette.divider, 0.3)}`,
                    borderRadius: '20px',
                    p: '4px 12px 4px 4px',
                    cursor: 'pointer',
                    '&:hover': {
                      backgroundColor: alpha(theme.palette.primary.main, 0.05),
                    },
                  }}
                  onClick={handleOpenUserMenu}
                >
                  <Avatar
                    sx={{
                      width: 32,
                      height: 32,
                      backgroundColor: user?.avatar ? 'transparent' : theme.palette.primary.main,
                      fontSize: '0.875rem',
                      marginRight: 1,
                    }}
                    src={user?.avatar || undefined}
                  >
                    {getInitials()}
                  </Avatar>
                  <Typography
                    variant="body2"
                    sx={{
                      fontWeight: 500,
                      display: { xs: 'none', sm: 'block' },
                    }}
                  >
                    {user?.username || '用户'}
                  </Typography>
                </Box>
                <Menu
                  sx={{ mt: '45px' }}
                  id="menu-appbar"
                  anchorEl={anchorElUser}
                  anchorOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  keepMounted
                  transformOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  open={Boolean(anchorElUser)}
                  onClose={handleCloseUserMenu}
                >
                  {userMenuItems.map((setting) => (
                    <MenuItem key={setting.title} onClick={() => {
                      handleCloseUserMenu();
                      router.push(setting.href);
                    }}>
                      <Box sx={{ display: 'flex', alignItems: 'center' }}>
                        {setting.icon && <Box sx={{ mr: 1 }}>{setting.icon}</Box>}
                        <Typography textAlign="center">{setting.title}</Typography>
                      </Box>
                    </MenuItem>
                  ))}
                  {/* 添加分隔线 */}
                  <Box sx={{ my: 1, mx: 2, borderTop: 1, borderColor: 'divider' }} />
                  <MenuItem onClick={handleLogout}>
                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                      <LogoutIcon fontSize="small" sx={{ mr: 1 }} />
                      <Typography textAlign="center">退出登录</Typography>
                    </Box>
                  </MenuItem>
                </Menu>
              </>
            ) : (
              <Box sx={{ display: 'flex' }}>
                <Button
                  variant="text"
                  component={Link}
                  href="/register"
                  sx={{ mr: 1 }}
                >
                  注册
                </Button>
                <Button
                  variant="contained"
                  color="primary"
                  component={Link}
                  href="/login"
                >
                  登录
                </Button>
              </Box>
            )}
          </Box>
        </Toolbar>
      </Container>
    </AppBar>
  );
}

export default Navbar;
